package cj.web.marry.controllers;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.EnumSet;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.BaseController;
import cj.web.mall.dao.UserDAO;
import cj.web.marry.constants.EducationEnum;
import cj.web.marry.constants.MemberComTypeEnum;
import cj.web.marry.constants.SalaryEnum;
import cj.web.marry.constants.SexEnum;
import cj.web.marry.constants.XQIsChildrenEnum;
import cj.web.marry.constants.XQIsMarryEnum;
import cj.web.marry.constants.XQIsOpenEnum;
import cj.web.marry.constants.XQRoomOrCarEnum;
import cj.web.marry.dao.AppTokenDAO;
import cj.web.marry.dao.CmpActDAO;
import cj.web.marry.dao.PubActDAO;
import cj.web.marry.utils.ImagePicture;

@Path("xqLoginPub")
public class XQLoginPubController extends BaseController{
	
	public final static String image_jpg=".jpg";
	
	public final static String image_png=".png";
	
	@Autowired
	private UserDAO userDao;
	@Autowired
	private AppTokenDAO appTokenDao;
	@Autowired
	private CmpActDAO cmpActDAO;
	@Autowired
	private PubActDAO pubActDAO;
	
	/**
	 * 
	 * @param model
	 * @param returnPage
	 * @return
	 */
	@Get("login")
	public String login(Model model, @Param("returnPage")String returnPage){
		if(returnPage != null && returnPage.length() > 0){
			model.add("returnPage", returnPage);
		}
		return "/views/marry/meet/login.vm";
	}
	
	/**
	 * 
	 * @param phone
	 * @param token
	 * @param returnPage
	 * @param response
	 * @return
	 */
	@Post("register")
	public synchronized String register(@Param("phone")String phone, @Param("token")String token, 
			@Param("returnPage")String returnPage, HttpServletResponse response){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if( appTokenDao.queryToken(phone, token) > 0 ){
			if( userDao.isRegister(phone) == 0 ){
				userDao.register(phone);
			}
			
			int buyerId = userDao.getBuyerId(phone);
			int isExist = userDao.isExistMemberDetail(buyerId);
			
			if(isExist==0){
				jo.put("returnPage", "xqLoginPub/perfectUser?returnPage=" + returnPage);
				//return "r:../xqLoginPub/perfectUser?returnPage=" + returnPage;
			}else{
				jo.put("returnPage", returnPage);
			}
			
			setCookie(response, "phone", phone);
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 完善个人资料
	 * @param returnPage
	 * @param model
	 * @return
	 */
	@Get("perfectUser")
	public String perfectUser(@Param("returnPage")String returnPage,Model model){
		if(returnPage != null && returnPage.length() > 0){
			model.add("returnPage", returnPage);
		}
		model.add("ComTypeEnum",EnumSet.allOf(MemberComTypeEnum.class));
        model.add("SexEnum",EnumSet.allOf(SexEnum.class));
        model.add("IsMarryEnum",EnumSet.allOf(XQIsMarryEnum.class));
        model.add("IsOpenEnum",EnumSet.allOf(XQIsOpenEnum.class));
        model.add("IsChildrenEnum",EnumSet.allOf(XQIsChildrenEnum.class));
        model.add("XQRoomOrCarEnum",EnumSet.allOf(XQRoomOrCarEnum.class));
        model.add("EducationEnum",EnumSet.allOf(EducationEnum.class));
        model.add("SalaryEnum",EnumSet.allOf(SalaryEnum.class));
		return "/views/marry/meet/completeMsg.vm";
	}
	
	/**
	 * 完善个人信息
	 * @param name
	 * @param files
	 * @param identityCard
	 * @param nickname
	 * @param sex
	 * @param isMarry
	 * @param weight
	 * @param height
	 * @param isOpen
	 * @param education
	 * @param school
	 * @param profession
	 * @param money
	 * @param roomOrCar
	 * @param isChildren
	 * @param infor
	 * @param selection
	 * @param province
	 * @param city
	 * @param area
	 * @param degree
	 * @param request
	 * @return
	 */
	@Post("perfect")
	public synchronized String perfect(@Param("name")String name,@Param("photo") String photo,
			@Param("identityCard")String identityCard,@Param("nickname")String nickname,
			@Param("sex")int sex,@Param("isMarry")int isMarry,@Param("weight")String weight,@Param("height")String height,
			@Param("isOpen")int isOpen,@Param("education")String education,@Param("school")String school,
			@Param("profession")String profession,@Param("money")String money,@Param("roomOrCar")String roomOrCar,
			@Param("isChildren")int isChildren,@Param("infor")String infor,@Param("selection")String selection,
			@Param("province")String province,@Param("city")String city,@Param("area")String area,@Param("degree")int degree,
			@Param("company")String company,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			String phone = getCookieValueByName(request, "phone");
			int buyerId = userDao.getBuyerId(phone);
			
			area=province.split(" ")[2];
			city=province.split(" ")[1];
			province=province.split(" ")[0];
            userDao.create(buyerId, MemberComTypeEnum.NUM_0.getValue(), -1, name, identityCard, photo, 
					nickname, sex, isMarry, weight, height, isOpen, education, school,profession, money, roomOrCar, 
					isChildren, infor, selection, province, city, area, phone,company);
            
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Post("loadPhoto")
    public String loadPhoto(@Param("croppedImage") MultipartFile[] files,@Param("degree")int degree,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String returnImgPath = uploadPhoto(files, degree);
		jo.put("returnImgPath", returnImgPath);
		return "@"+jo.toString();
    }
	
	/**
	 * 上传头像
	 * @param files
	 * @param degree
	 * @return
	 */
	private String uploadPhoto(MultipartFile[] files,int degree){
		String returnImgPath = "";
		try {
			String path = ReadConfigProperties.getValue("uploadFilePath");// 文件保存路径  
			
			// 判断文件列表是否为空  
	        if (files != null && files.length > 0) {
	        	for(MultipartFile file : files){
	        		try {  
		            	// 判断文件是否存在，不存在创建文件
		            	Map rep = ReturnUUID.getFolder(path);
		            	// 所在的全路径
		            	path = rep.get("allpath").toString();
		            	// 文件名
		                String fileName =  ReturnUUID.getUUID(); 
		                // 统一转换为JPG
		                String newFileName = fileName+image_jpg;
		                // 转存文件  
		                file.transferTo(new File(path+"/"+newFileName));  
		                if(90==degree){
		                	//反转
		                	
		                	//上传得图片
			                BufferedImage bi = ImageIO.read(new File(path+"/"+newFileName));
			                //翻转90度
			        		BufferedImage newsImage = ImagePicture.rotateImage(bi);
			        		//统一转换为PNG
			                String newFileName_png = fileName+image_png;
			                //图片反转另存PNG
			        		ImageIO.write(newsImage, "png", new File(path+"/"+newFileName_png));
			        		
			        		returnImgPath = rep.get("filepath")+"/"+newFileName_png;
		                }else{
		                	//正常
		                	
			                returnImgPath = rep.get("filepath")+"/"+newFileName;
		                }
	                } catch (Exception e) {  
	                	// TODO: handle exception
	                    e.printStackTrace();  
	                }  
	        	}
	        } 
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();  
		}
		return returnImgPath;
	}
}